<?php

require_once "init.inc.php";

$store = $_REQUEST['store'];
$query = $_REQUEST['query'];

function prettyPrintQuery($queryInfo) {
	$pp = new PrettyPrintQuery($queryInfo);
	return $pp->getQuery();
}

if ( $store && $query ) {
	
	$response = true;
	$failed = false;
	$errmess = false;
	$changed = false;
	$optimised = false;
	
	if ( ! $failed ) {

		$parser = ARC2::getSPARQLParser();
	
		/* parse a query */
		$parser->parse($query);
		if (!$parser->getErrors()) {
		  $q_infos = $parser->getQueryInfos();
		  //print_r($q_infos);
		}
		else {
		  $failed = true;
		  $errmess =  "invalid query: " . print_r($parser->getErrors(),true) . "\n";
		}
	}
	
	
	if ( ! $failed ) {

		$optimiser = new Optimiser(SchemaStats::getTheSchemaStats($store));

		$queryInfo = $parser->getQueryInfos();
		$optimised = $queryInfo;
		
		$optimised_query = $optimiser->optimise($queryInfo);
		
		if ( $optimiser->status == 'FAIL' ) {
			$failed = true;
		 	$errmess =   implode("\n",$optimiser->reason) ."\n";
		} else {
			$old = prettyPrintQuery($queryInfo);
			$optimised = prettyPrintQuery($optimised_query);
			$changed = $old != $optimised;
		}
	}

}


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>SPARQL Query Optimiser</title>

<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>

<body>
<div id="wrap">
<div id="content">
  <div class="gutter">
  <h1>SPARQL Query Optimiser</h1>

<?php
  if ( $response ) :
	if ( $failed ) :
?>
      <p class="notice"> sorry optimisation failed :-(</p>
<?php
	elseif ( $changed && $optimised ) :
?>
      <p class="notice"> query optimised - alternative below </p>
<?php
	else :
?>
      <p class="notice"> optimisation OK, but no change </p>
<?php
	endif;
  endif; // response
?>

  <form method="post" action="optimise.php">
    <fieldset>
      <legend>Optimise SPARQL query</legend>
      <div>
        <label for="store">Store URL:</label><br class="field"/>
        <input name="store" type="text" id="store" size="80" maxlength="255" value="<?php echo htmlentities($store); ?>" />
      </div>  
      <div>
        <label for="query">SPARQL query:</label><br class="field"/>
        <textarea id="query" name="query" class="text" rows="10" cols="80"><?php echo htmlentities($query); ?></textarea>
      </div>  
      <div><input type="submit" class="submit default" value="Optimise" /><br  class="field" /></div>
<?php
	if ( $changed && $optimised ) :
?>
      <div>
        <label for="query">optimised query:</label><br class="field"/>
        <pre class="text"><?php echo htmlentities($optimised); ?></pre>
      </div>  
<?php
	endif;
?>

    </fieldset>
  </form>

  </div>
</div>
  <ul id="footer">
    <li id="learn"><a href="http://n2.talis.com/wiki/Platform_API">learn more</a></li>

</ul></div>

</body>
</html>